package org.bot.plugin.web.event;

import org.bot.api.event.DataStorage;
import org.bot.api.event.EventName;
import org.bot.api.event.Events;
import org.bot.api.flow.FlowNode;
import org.bot.api.util.StringUtil;
import org.bot.plugin.web.util.WebApi;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @author 沧月
 * @create 0012 2023/9/12 17:34
 * @description <执行JavaScript代码>
 * <p>
 * config   {"cmd":"org.bot.plugin.web.event.WebScript","arg":"JavaScript代码"}
 */

@Component
@EventName("执行脚本")
public class WebScript implements Events {

    @Autowired
    WebApi webApi;

    @Override
    public Object exec(FlowNode note, DataStorage data) {
        if (StringUtil.isNotNull(note.getDataIndex())) {
            String dataIndex = note.getDataIndex();
            String[] array = dataIndex.split(",");
            Object[] javaScriptParam = new Object[array.length];
            for (int i = 0; i < array.length; i++) {
                Object o = data.get(array[i]);
                javaScriptParam[i] = o == null ? "" : o.toString();
            }
            return webApi.script(webApi.getWebDriver(note), note.getArg(), javaScriptParam);
        }
        return webApi.script(webApi.getWebDriver(note), note.getArg());
    }

}
